#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_ReportLabStakerReport, COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings


def BuildStakerForm(SpecialBuildFormInfo):
    if(SpecialBuildFormInfo):
        QueryUserName=SpecialBuildFormInfo['QueryUserName']
        ShowStakerIndicator=SpecialBuildFormInfo['ShowStakerIndicator']
        ShowOutToConstructionIndicator=SpecialBuildFormInfo['ShowOutToConstructionIndicator']
        ShowVerificationIndicator=SpecialBuildFormInfo['ShowVerificationIndicator']
        ShowArchivedIndicator=SpecialBuildFormInfo['ShowArchivedIndicator']
        ShowDeletedIndicator=SpecialBuildFormInfo['ShowDeletedIndicator']
    else:
        QueryUserName='All'
        ShowStakerIndicator=False
        ShowOutToConstructionIndicator=False 
        ShowVerificationIndicator=False 
        ShowArchivedIndicator=False 
        ShowDeletedIndicator=False

    Dict={}
    StakerWorkOrderUserChoices=[]
    StakerWorkOrderUsers=StakerWorkOrder.objects.all().order_by('Name')
    TempUsers=[]
    while(True):
        StakerWorkOrderUsers=StakerWorkOrder.objects.all().order_by('UserName')
        for i in TempUsers:
            StakerWorkOrderUsers=StakerWorkOrderUsers.exclude(UserName=i)
        if(StakerWorkOrderUsers):
            TempUsers.append(StakerWorkOrderUsers[0].UserName)
        else:
            break
    StakerWorkOrderUserChoices.append(['All', 'All'])
    for i in TempUsers:
        StakerWorkOrderUserChoices.append([i,i])
    Dict['QueryUserName']=forms.ChoiceField(StakerWorkOrderUserChoices, required=False)

    #Selection Area
    #Create a List of Staker Work Orders that meet the criteria from the Query Area
    StakerWorkOrderChoices=[]
    StakerWorkOrderChoices.append(['-2', 'None'])
    StakerWorkOrderChoices.append(['-1', 'New'])

    if(QueryUserName == 'All'):
        StakerWorkOrders=StakerWorkOrder.objects.order_by('StakerPhaseStartDate','Name')
    else:
        StakerWorkOrders=StakerWorkOrder.objects.filter(UserName=QueryUserName).order_by('StakerPhaseStartDate','Name')

    #Filter the Archived Orders using the DB, then use Python code to filter the rest, should avoid a major performance hit as
    #most orders should go to Archived over time #FIXME probably...
    StakerWorkOrders=StakerWorkOrders.filter(ArchivedIndicator=ShowArchivedIndicator)
    if(not ShowArchivedIndicator):
        Temp=[]
        for i in StakerWorkOrders:
            CurrentPhase=i.GetCurrentPhase()
            if(CurrentPhase == 'Delete' and ShowDeletedIndicator):
                Temp.append(i)
            elif(CurrentPhase == 'Verification' and ShowVerificationIndicator):
                Temp.append(i)
            elif(CurrentPhase == 'OutToConstruction' and ShowOutToConstructionIndicator):
                Temp.append(i)
            elif(CurrentPhase == 'Staker' and ShowStakerIndicator):
                Temp.append(i)
        StakerWorkOrders=Temp

    for i in StakerWorkOrders:
        if i.StakerPhaseStartDate:
            StakerWorkOrderChoices.append([i.id, str(i.StakerPhaseStartDate) + ': ' + str(i.WorkOrderNumber) + ' ' + str(i.Name)])
        else:
            StakerWorkOrderChoices.append([i.id, str(i.WorkOrderNumber) + ' ' + str(i.Name)])
    Dict['StakerWorkOrders']=forms.ChoiceField(StakerWorkOrderChoices, required=False)

    #Query Options
    Dict['ShowStakerIndicator']=forms.BooleanField()
    Dict['ShowOutToConstructionIndicator']=forms.BooleanField()
    Dict['ShowVerificationIndicator']=forms.BooleanField()
    Dict['ShowArchivedIndicator']=forms.BooleanField()
    Dict['ShowDeletedIndicator']=forms.BooleanField()
    Dict['SelectWorkOrderNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    #Main Form Area
    Dict['DeleteIndicator']=forms.BooleanField()
    Dict['UndeleteIndicator']=forms.BooleanField()
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    Dict['StakerWorkOrderid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['StakerWorkOrderUserName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['StakerWorkOrderChangeUserNameIndicator']=forms.BooleanField()
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    #The following fields are ones that appear at the top of the 1st page of a Staker Work Order
    Dict['HazardsAssociatedWithJobIndicator']=forms.BooleanField()
    Dict['WorkProcedureInvolvedIndicator']=forms.BooleanField()
    Dict['SpecialPrecautionsIndicator']=forms.BooleanField()
    Dict['EnergySourceControlsIndicator']=forms.BooleanField()
    Dict['PPERequirementsIndicator']=forms.BooleanField()
    Dict['TailgateDiscussionIndicator']=forms.BooleanField()
    Dict['CheckWhereSepticTankIsIndicator']=forms.BooleanField()
    Dict['WorkPlanReferenceIndicator']=forms.BooleanField()
    Dict['NewConstructionIndicator']=forms.BooleanField()
    Dict['SystemImprovementIndicator']=forms.BooleanField()
    Dict['ReplacementIndicator']=forms.BooleanField()
    Dict['Retire_No_ReplacementIndicator']=forms.BooleanField()
    Dict['GeneralFundsIndicator']=forms.BooleanField()
    Dict['No_OfServicesOH']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['No_OfServicesUG']=forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['Wire']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['LoanNo']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['Substation']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['MapNo']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['LocationNextTo']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['CalhounCountyIndicator']=forms.BooleanField()
    Dict['OrangeburgCountyIndicator']=forms.BooleanField()
    Dict['LexingtonCountyIndicator']=forms.BooleanField()
    Dict['RichlandCountyIndicator']=forms.BooleanField()
    Dict['KershawCountyIndicator']=forms.BooleanField()
    Dict['SumterCountyIndicator']=forms.BooleanField()
    Dict['WorkOrderNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['W_P']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['N_W_P']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['EngineerStaked']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['EngineerChecked']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['EngineerReleasedForConst']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['Co_PermitNo']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['PUPS']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['NewR_WIndicator']=forms.BooleanField()
    Dict['R_WToBeCutIndicator']=forms.BooleanField()
    Dict['R_WCutDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['ExistingR_WIndicator']=forms.BooleanField()
    Dict['StakerWorkOrderid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['EstimateOnlyIndicator']=forms.BooleanField()
    #The Following Refer to Dates and the "Phase" of a Staker Work Order and should not be changed directly (might change mind on this)
    Dict['CreateDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['StakerPhaseStartIndicator']=forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
    Dict['StakerPhaseStartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['OutToConstructionStartIndicator']=forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
    Dict['OutToConstructionStartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['VerificationPhaseStartIndicator']=forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
    Dict['VerificationPhaseStartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['ArchivedIndicator']=forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
    Dict['ArchivedDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['CreateDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
    Dict['DeletedIndicator']=forms.BooleanField()
    Dict['CalculateExtentsIndicator']=forms.BooleanField()
    Dict['StartPhaseOutToConstructionIndicator']=forms.BooleanField()
    Dict['StartPhaseVerificationIndicator']=forms.BooleanField()
    Dict['StartPhaseArchiveIndicator']=forms.BooleanField()
    Dict['CancelPhaseOutToConstructionIndicator']=forms.BooleanField()
    Dict['CancelPhaseVerificationIndicator']=forms.BooleanField()
    Dict['MinimumX']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['MinimumY']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['MaximumX']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['MaximumY']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['ArchivedScannedWorkOrderFileName']=forms.FileField()
    Dict['ArchivedInspectedWorkOrderFileName']=forms.FileField()
    Dict['StationListOverride']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'14'}))
    Dict['StationSortByDistanceIndicator']=forms.BooleanField()
    Dict['DisplayMapOutlineIndicator']=forms.BooleanField()
    Dict['ClearFormIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessStakerFormSelectWorkOrder(form, UserName):
    try:
        SelectWorkOrderNumber=form.data['SelectWorkOrderNumber']
    except:
        SelectWorkOrderNumber=''
    if(not SelectWorkOrderNumber):
        return form
    try:
        stakerWorkOrder=StakerWorkOrder.objects.filter(WorkOrderNumber=SelectWorkOrderNumber)[0]
    except:
        return form
    #If here, a valid stakerWorkOrder has been selected, so update the form to reflect it:
    form.data['ShowStakerIndicator']=stakerWorkOrder.StakerPhaseStartIndicator
    form.data['ShowOutToConstructionIndicator']=stakerWorkOrder.OutToConstructionStartIndicator
    form.data['ShowVerificationIndicator']=stakerWorkOrder.VerificationPhaseStartIndicator
    form.data['ShowArchivedIndicator']=stakerWorkOrder.ArchivedIndicator
    form.data['ShowDeletedIndicator']=stakerWorkOrder.DeletedIndicator
    form.data['SelectWorkOrderNumber']=''
    form.data['QueryUserName']=stakerWorkOrder.UserName
    form.data['StakerWorkOrders']=stakerWorkOrder.id
    return form

    

def ProcessStakerForm(form, UserName, request):
    #Extract Data Out Of The Staker Work Order Form
    try:
        SelectedWorkOrderid=int(form.data['StakerWorkOrders'])
    except KeyError:
        SelectedWorkOrderid=''
    NewIndicator=False
    if(SelectedWorkOrderid == -2):   #Explicit None Choice
        SelectedWorkOrderid=''
    elif(SelectedWorkOrderid == -1):  #New Choice
        NewIndicator=True 
        SelectedWorkOrder=''     
    ShowDeletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowDeletedIndicator')
    StakerWorkOrderChangeUserNameIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StakerWorkOrderChangeUserNameIndicator')
    ShowArchivedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowArchivedIndicator')
    DeleteIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteIndicator')
    UndeleteIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UndeleteIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    try:
        StakerWorkOrderid=int(form.data['StakerWorkOrderid'])
    except (ValueError, KeyError):
        StakerWorkOrderid=None
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')

    HazardsAssociatedWithJobIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'HazardsAssociatedWithJobIndicator')
    WorkProcedureInvolvedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkProcedureInvolvedIndicator')
    SpecialPrecautionsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SpecialPrecautionsIndicator')
    EnergySourceControlsIndicator=COOPGIS_FormMisc.FormGetBoolean(form,'EnergySourceControlsIndicator')
    PPERequirementsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PPERequirementsIndicator')
    TailgateDiscussionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'TailgateDiscussionIndicator')
    CheckWhereSepticTankIsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CheckWhereSepticTankIsIndicator')
    WorkPlanReferenceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkPlanReferenceIndicator')
    NewConstructionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewConstructionIndicator')
    SystemImprovementIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SystemImprovementIndicator')
    ReplacementIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReplacementIndicator')
    Retire_No_ReplacementIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'Retire_No_ReplacementIndicator')
    GeneralFundsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'GeneralFundsIndicator')
    No_OfServicesOH=COOPGIS_FormMisc.FormGetInteger(form, 'No_OfServicesOH', None)
    No_OfServicesUG=COOPGIS_FormMisc.FormGetInteger(form, 'No_OfServicesUG', None)
    Wire=COOPGIS_FormMisc.FormGetString(form, 'Wire')
    LoanNo=COOPGIS_FormMisc.FormGetString(form, 'LoanNo')
    Substation=COOPGIS_FormMisc.FormGetString(form, 'Substation')
    MapNo=COOPGIS_FormMisc.FormGetString(form, 'MapNo')
    LocationNextTo=COOPGIS_FormMisc.FormGetString(form, 'LocationNextTo')
    CalhounCountyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CalhounCountyIndicator')
    OrangeburgCountyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'OrangeburgCountyIndicator')
    LexingtonCountyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'LexingtonCountyIndicator')
    RichlandCountyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RichlandCountyIndicator')
    KershawCountyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'KershawCountyIndicator')
    SumterCountyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SumterCountyIndicator')
    EstimateOnlyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'EstimateOnlyIndicator')
    WorkOrderNumber=COOPGIS_FormMisc.FormGetString(form, 'WorkOrderNumber')
    W_P=COOPGIS_FormMisc.FormGetString(form, 'W_P')
    N_W_P=COOPGIS_FormMisc.FormGetString(form, 'N_W_P')
    EngineerStaked=COOPGIS_FormMisc.FormGetString(form, 'EngineerStaked')
    EngineerChecked=COOPGIS_FormMisc.FormGetString(form, 'EngineerChecked')
    EngineerReleasedForConst=COOPGIS_FormMisc.FormGetString(form, 'EngineerReleasedForConst')
    Co_PermitNo=COOPGIS_FormMisc.FormGetString(form, 'Co_PermitNo')
    PUPS=COOPGIS_FormMisc.FormGetString(form, 'PUPS')
    NewR_WIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewR_WIndicator')
    R_WToBeCutIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'R_WToBeCutIndicator')
    R_WCutDate=COOPGIS_FormMisc.FormGetString(form, 'R_WCutDate')  #This is treated as a string in the DB
    ExistingR_WIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ExistingR_WIndicator')
    try:
        CreateDate=COOPGIS_String.StringToDate(form.data['CreateDate'])
    except KeyError:
        CreateDate=None
    try:
        StakerPhaseStartIndicator=bool(form.data['StakerPhaseStartIndicator'] == 'on')
    except KeyError:
        StakerPhaseStartIndicator=True #This phase starts when a Staker Work Order is created
    try:
        StakerPhaseStartDate=COOPGIS_String.StringToDate(form.data['StakerPhaseStartDate'])
    except KeyError:
        StakerPhaseStartDate=None
    OutToConstructionStartIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'OutToConstructionStartIndicator')
    try:
        OutToConstructionStartDate=COOPGIS_String.StringToDate(form.data['OutToConstructionStartDate'])
    except KeyError:
        OutToConstructionStartDate=None
    VerificationPhaseStartIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'VerificationPhaseStartIndicator')

    try:
        VerificationPhaseStartDate=COOPGIS_String.StringToDate(form.data['VerificationPhaseStartDate'])
    except KeyError:
        VerificationPhaseStartDate=None

    ArchivedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ArchivedIndicator')
    try:
        ArchivedDate=COOPGIS_String.StringToDate(form.data['ArchivedDate'])
    except KeyError:
        ArchivedDate=None
    try:
        CreateDate=COOPGIS_String.StringToDate(form.data['CreateDate'])
    except:
        CreateDate=None
    DeletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeletedIndicator')
    AutomaticallyRecalculateExtentsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'AutomaticallyRecalculateExtentsIndicator')
    StartPhaseOutToConstructionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StartPhaseOutToConstructionIndicator')
    StartPhaseVerificationIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StartPhaseVerificationIndicator')
    StartPhaseArchiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StartPhaseArchiveIndicator')
    CancelPhaseOutToConstructionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CancelPhaseOutToConstructionIndicator')
    CancelPhaseVerificationIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CancelPhaseVerificationIndicator')
    MinimumX=COOPGIS_FormMisc.FormGetFloat(form, 'MinimumX', None)
    MinimumY=COOPGIS_FormMisc.FormGetFloat(form, 'MinimumY', None)
    MaximumX=COOPGIS_FormMisc.FormGetFloat(form, 'MaximumX', None)
    MaximumY=COOPGIS_FormMisc.FormGetFloat(form, 'MaximumY', None)
    try:
        StakerPhaseStartIndicator=bool(form.data['StakerPhaseStartIndicator'] == 'on')
    except KeyError:
        StakerPhaseStartIndicator=True #This phase starts when a Staker Work Order is created
    try:
        StakerPhaseStartDate=COOPGIS_String.StringToDate(form.data['StakerPhaseStartDate'])
        if(not StakerPhaseStartDate):
            StakerPhaseStartDate=datetime.datetime.now()
    except KeyError:
        StakerPhaseStartDate=datetime.datetime.now()
    OutToConstructionStartIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'OutToConstructionStartIndicator')
    try:
        OutToConstructionStartDate=COOPGIS_String.StringToDate(form.data['OutToConstructionStartDate'])
    except KeyError:
        OutToConstructionStartDate=None
    VerificationPhaseStartIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'VerificationPhaseStartIndicator')
    try:
        VerificationPhaseStartDate=COOPGIS_String.StringToDate(form.data['VerificationPhaseStartDate'])
    except KeyError:
        VerificationPhaseStartDate=None
    StartPhaseArchiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StartPhaseArchiveIndicator')
    try:
        ArchivedDate=COOPGIS_String.StringToDate(form.data['ArchivedDate'])
    except KeyError:
        ArchivedDate=None
    try: 
        ArchivedScannedWorkOrderFile=request.FILES['ArchivedScannedWorkOrderFileName']
    except:
        ArchivedScannedWorkOrderFile=None
    try:
        ArchivedInspectedWorkOrderFile=request.FILES['ArchivedInspectedWorkOrderFileName']
    except:
        ArchivedInspectedWorkOrderFile=None
    StationListOverride=COOPGIS_FormMisc.FormGetString(form, 'StationListOverride')
    StationSortByDistanceIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'StationSortByDistanceIndicator')
    DisplayMapOutlineIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DisplayMapOutlineIndicator')
    #End Extract Data Out of Staker Work Order Form

    #Start Actions based on Form Fields:
    stakerWorkOrder=None
    #Start/Cancel Phase Indicators represent actions, so perform those actions on the form inputs...
    if(StartPhaseOutToConstructionIndicator):
        if(not OutToConstructionStartIndicator):
            OutToConstructionStartIndicator=True
            OutToConstructionStartDate=datetime.datetime.now()
    if(StartPhaseVerificationIndicator and OutToConstructionStartIndicator):
        if(not VerificationPhaseStartIndicator):
            VerificationPhaseStartIndicator=True
            VerificationPhaseStartDate=datetime.datetime.now()
    PerformArchiveTasks=False
    if(StartPhaseArchiveIndicator and VerificationPhaseStartIndicator and not NewIndicator): 
        #To be put into Archive Stage, a Staker Work Order requires that a scanned image be uploaded.  This is verified before applying the changes  
        #It also can only be done on the Server.  This is checked here.
        #Once in Archive Status, the Staker Work Order is DONE in the GIS, it cannot be edited any further under normal circumstances
        if((not ArchivedIndicator) and djangoproject.settings.COOPGISServerIndicator):
            #ArchivedScannedWorkOrderFileName will be checked before saving, otherwise ArchivedIndicator and ArchivedDate will be set back to False/None
            ArchivedIndicator=True
            ArchivedDate=datetime.datetime.now()
            PerformArchiveTasks=True 
            # and (PerformArchiveTasks or not ArchivedIndicator) #used to prevent working on a staker work order to be archived, 
                                                                #except on the same postback that is sending it to archive status 
    ArchiveStatusMessage=''
    if(CancelPhaseOutToConstructionIndicator):
        if(not ArchivedIndicator and not VerificationPhaseStartIndicator):
            OutToConstructionStartIndicator=False
            OutToConstructionStartDate=None
    if(CancelPhaseVerificationIndicator):
        if(not ArchivedIndicator):
            VerificationPhaseStartIndicator=False
            VerificationPhaseStartDate=None    
    if(NewIndicator and (PerformArchiveTasks or not ArchivedIndicator)):
        if(Name):
            if(StakerWorkOrder.objects.filter(Name__exact=Name)):
                Append=1
                while(StakerWorkOrder.objects.filter(Name__exact=Name + '_' + str(Append))):
                    Append=Append+1
                Name=Name + '_' + str(Append)           
            command=Command() 
            command=command.Create(Name='CreateStakerWorkOrder', StakerWorkOrderName=Name, Description=Description, 
                               HazardsAssociatedWithJobIndicator=HazardsAssociatedWithJobIndicator,
                               WorkProcedureInvolvedIndicator=WorkProcedureInvolvedIndicator, SpecialPrecautionsIndicator=SpecialPrecautionsIndicator,
                               EnergySourceControlsIndicator=EnergySourceControlsIndicator, PPERequirementsIndicator=PPERequirementsIndicator,
                               TailgateDiscussionIndicator=TailgateDiscussionIndicator, CheckWhereSepticTankIsIndicator=CheckWhereSepticTankIsIndicator,
                               WorkPlanReferenceIndicator=WorkPlanReferenceIndicator, NewConstructionIndicator=NewConstructionIndicator,
                               SystemImprovementIndicator=SystemImprovementIndicator, ReplacementIndicator=ReplacementIndicator,
                               Retire_No_ReplacementIndicator=Retire_No_ReplacementIndicator, GeneralFundsIndicator=GeneralFundsIndicator,
                               No_OfServicesOH=No_OfServicesOH, No_OfServicesUG=No_OfServicesUG, Wire=Wire, LoanNo=LoanNo, Substation=Substation,
                               MapNo=MapNo, LocationNextTo=LocationNextTo, CalhounCountyIndicator=CalhounCountyIndicator,    
                               OrangeburgCountyIndicator=OrangeburgCountyIndicator, LexingtonCountyIndicator=LexingtonCountyIndicator,
                               RichlandCountyIndicator=RichlandCountyIndicator, KershawCountyIndicator=KershawCountyIndicator,
                               SumterCountyIndicator=SumterCountyIndicator, WorkOrderNumber=WorkOrderNumber, W_P=W_P, N_W_P=N_W_P,
                               EngineerStaked=EngineerStaked, EngineerChecked=EngineerChecked, EngineerReleasedForConst=EngineerReleasedForConst,
                               Co_PermitNo=Co_PermitNo, PUPS=PUPS, NewR_WIndicator=NewR_WIndicator, R_WToBeCutIndicator=R_WToBeCutIndicator,
                               R_WCutDate=R_WCutDate, ExistingR_WIndicator=ExistingR_WIndicator, 
                               StakerPhaseStartIndicator=StakerPhaseStartIndicator, StakerPhaseStartDate=StakerPhaseStartDate, 
                               OutToConstructionStartIndicator=OutToConstructionStartIndicator, OutToConstructionStartDate=OutToConstructionStartDate,
                               VerificationPhaseStartIndicator=VerificationPhaseStartIndicator, VerificationPhaseStartDate=VerificationPhaseStartDate,
                               ArchivedIndicator=ArchivedIndicator, ArchivedDate=ArchivedDate, CreateDate=CreateDate, DeletedIndicator=DeletedIndicator,                               
                               CommandUserName=UserName, MinimumX=MinimumX, MinimumY=MinimumY,
                               MaximumX=MaximumX, MaximumY=MaximumY, AutomaticallyRecalculateExtentsIndicator=AutomaticallyRecalculateExtentsIndicator,
                               StationListOverride=StationListOverride, DisplayMapOutlineIndicator=DisplayMapOutlineIndicator,
                               EstimateOnlyIndicator=EstimateOnlyIndicator)
            stakerWorkOrder=command.Process()
            SelectedWorkOrderid=stakerWorkOrder.id
    elif((PerformArchiveTasks or not ArchivedIndicator)):
        if(StakerWorkOrderid):
            try:
                stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=StakerWorkOrderid)[0]
            except:  
                stakerWorkOrder=None
            if(AutomaticallyRecalculateExtentsIndicator):
                MinimumX, MinimumY, MaximumX, MaximumY = stakerWorkOrder.CalculateExtents()
            if(stakerWorkOrder):
                if(PerformArchiveTasks):  #If here, staker work order is going into archive mode, already on server
                    ArchiveStatusMessage, AttemptToArchiveSuccessIndicator=AttemptToArchive(request, stakerWorkOrder, UserName)
                    if(not AttemptToArchiveSuccessIndicator):
                        ArchivedIndicator=False
                        ArchivedDate=None
                if(stakerWorkOrder.ResidesOnServerIndicator):
                    command=Command() 
                    command=command.Create(Name='EditStakerWorkOrder', StakerWorkOrderid=StakerWorkOrderid, StakerWorkOrderName=Name, Description=Description, 
                                       HazardsAssociatedWithJobIndicator=HazardsAssociatedWithJobIndicator,
                                       WorkProcedureInvolvedIndicator=WorkProcedureInvolvedIndicator, SpecialPrecautionsIndicator=SpecialPrecautionsIndicator,
                                       EnergySourceControlsIndicator=EnergySourceControlsIndicator, PPERequirementsIndicator=PPERequirementsIndicator,
                                       TailgateDiscussionIndicator=TailgateDiscussionIndicator, CheckWhereSepticTankIsIndicator=CheckWhereSepticTankIsIndicator,
                                       WorkPlanReferenceIndicator=WorkPlanReferenceIndicator, NewConstructionIndicator=NewConstructionIndicator,
                                       SystemImprovementIndicator=SystemImprovementIndicator, ReplacementIndicator=ReplacementIndicator,
                                       Retire_No_ReplacementIndicator=Retire_No_ReplacementIndicator, GeneralFundsIndicator=GeneralFundsIndicator,
                                       No_OfServicesOH=No_OfServicesOH, No_OfServicesUG=No_OfServicesUG, Wire=Wire, LoanNo=LoanNo, Substation=Substation,
                                       MapNo=MapNo, LocationNextTo=LocationNextTo, CalhounCountyIndicator=CalhounCountyIndicator,    
                                       OrangeburgCountyIndicator=OrangeburgCountyIndicator, LexingtonCountyIndicator=LexingtonCountyIndicator,
                                       RichlandCountyIndicator=RichlandCountyIndicator, KershawCountyIndicator=KershawCountyIndicator,
                                       SumterCountyIndicator=SumterCountyIndicator, WorkOrderNumber=WorkOrderNumber, W_P=W_P, N_W_P=N_W_P,
                                       EngineerStaked=EngineerStaked, EngineerChecked=EngineerChecked, EngineerReleasedForConst=EngineerReleasedForConst,
                                       Co_PermitNo=Co_PermitNo, PUPS=PUPS, NewR_WIndicator=NewR_WIndicator, R_WToBeCutIndicator=R_WToBeCutIndicator,
                                       R_WCutDate=R_WCutDate, ExistingR_WIndicator=ExistingR_WIndicator,
                                       StakerPhaseStartIndicator=StakerPhaseStartIndicator, StakerPhaseStartDate=StakerPhaseStartDate, 
                                       OutToConstructionStartIndicator=OutToConstructionStartIndicator, OutToConstructionStartDate=OutToConstructionStartDate,
                                       VerificationPhaseStartIndicator=VerificationPhaseStartIndicator, VerificationPhaseStartDate=VerificationPhaseStartDate,
                                       ArchivedIndicator=ArchivedIndicator, ArchivedDate=ArchivedDate, CreateDate=CreateDate, DeletedIndicator=DeletedIndicator,   
                                       CommandUserName=UserName, MinimumX=MinimumX, MinimumY=MinimumY,
                                       MaximumX=MaximumX, MaximumY=MaximumY, AutomaticallyRecalculateExtentsIndicator=AutomaticallyRecalculateExtentsIndicator,
                                       StationListOverride=StationListOverride, StationSortByDistanceIndicator=StationSortByDistanceIndicator, 
                                       ChangeUserNameIndicator=StakerWorkOrderChangeUserNameIndicator, DisplayMapOutlineIndicator=DisplayMapOutlineIndicator,
                                       EstimateOnlyIndicator=EstimateOnlyIndicator)
                    stakerWorkOrder=command.Process()
                else:  #stakerWorkOrder does not reside on the server, so edit the command that created it and the stakerWorkOrder object
                    if(AutomaticallyRecalculateExtentsIndicator):
                        MinimumX, MinimumY, MaximumX, MaximumY = stakerWorkOrder.CalculateExtents()
                    CreateCommand=stakerWorkOrder.CreateCommand
                    CreateCommand.Set('StakerWorkOrderName',Name)
                    CreateCommand.Set('Description',Description)
                    CreateCommand.Set('HazardsAssociatedWithJobIndicator',HazardsAssociatedWithJobIndicator)
                    CreateCommand.Set('WorkProcedureInvolvedIndicator', WorkProcedureInvolvedIndicator)
                    CreateCommand.Set('SpecialPrecautionsIndicator', SpecialPrecautionsIndicator)
                    CreateCommand.Set('EnergySourceControlsIndicator', EnergySourceControlsIndicator)
                    CreateCommand.Set('PPERequirementsIndicator', PPERequirementsIndicator)
                    CreateCommand.Set('TailgateDiscussionIndicator', TailgateDiscussionIndicator)
                    CreateCommand.Set('CheckWhereSepticTankIsIndicator', CheckWhereSepticTankIsIndicator)
                    CreateCommand.Set('WorkPlanReferenceIndicator', WorkPlanReferenceIndicator)
                    CreateCommand.Set('NewConstructionIndicator', NewConstructionIndicator)
                    CreateCommand.Set('SystemImprovementIndicator', SystemImprovementIndicator)
                    CreateCommand.Set('ReplacementIndicator', ReplacementIndicator)
                    CreateCommand.Set('Retire_No_ReplacementIndicator', Retire_No_ReplacementIndicator)
                    CreateCommand.Set('GeneralFundsIndicator', GeneralFundsIndicator)
                    CreateCommand.Set('No_OfServicesOH', No_OfServicesOH)
                    CreateCommand.Set('No_OfServicesUG', No_OfServicesUG)
                    CreateCommand.Set('Wire', Wire)
                    CreateCommand.Set('LoanNo', LoanNo)
                    CreateCommand.Set('Substation', Substation)
                    CreateCommand.Set('MapNo', MapNo)
                    CreateCommand.Set('LocationNextTo', LocationNextTo)
                    CreateCommand.Set('CalhounCountyIndicator', CalhounCountyIndicator)
                    CreateCommand.Set('OrangeburgCountyIndicator', OrangeburgCountyIndicator)
                    CreateCommand.Set('RichlandCountyIndicator', RichlandCountyIndicator)
                    CreateCommand.Set('LexingtonCountyIndicator', LexingtonCountyIndicator)
                    CreateCommand.Set('SumterCountyIndicator', SumterCountyIndicator)
                    CreateCommand.Set('KershawCountyIndicator', KershawCountyIndicator)
                    CreateCommand.Set('WorkOrderNumber', WorkOrderNumber)
                    CreateCommand.Set('W_P', W_P)
                    CreateCommand.Set('N_W_P', N_W_P)
                    CreateCommand.Set('EngineerStaked', EngineerStaked)
                    CreateCommand.Set('EngineerChecked', EngineerChecked)
                    CreateCommand.Set('EngineerReleasedForConst', EngineerReleasedForConst)
                    CreateCommand.Set('Co_PermitNo', Co_PermitNo)
                    CreateCommand.Set('PUPS', PUPS)
                    CreateCommand.Set('NewR_WIndicator', NewR_WIndicator)
                    CreateCommand.Set('R_WToBeCutIndicator', R_WToBeCutIndicator)
                    CreateCommand.Set('R_WCutDate', R_WCutDate)
                    CreateCommand.Set('ExistingR_WIndicator', ExistingR_WIndicator)
                    CreateCommand.Set('StakerPhaseStartIndicator', StakerPhaseStartIndicator)
                    CreateCommand.Set('StakerPhaseStartDate', StakerPhaseStartDate)
                    CreateCommand.Set('OutToConstructionStartIndicator', OutToConstructionStartIndicator)
                    CreateCommand.Set('OutToConstructionStartDate', OutToConstructionStartDate)
                    CreateCommand.Set('VerificationPhaseStartIndicator', VerificationPhaseStartIndicator) 
                    CreateCommand.Set('VerificationPhaseStartDate', VerificationPhaseStartDate)
                    CreateCommand.Set('ArchivedIndicator', ArchivedIndicator)
                    CreateCommand.Set('ArchivedDate', ArchivedDate)
                    CreateCommand.Set('CreateDate', CreateDate)
                    CreateCommand.Set('DeletedIndicator', DeletedIndicator)        
                    CreateCommand.Set('MinimumX', MinimumX)
                    CreateCommand.Set('MinimumY', MinimumY)
                    CreateCommand.Set('MaximumX', MaximumX)
                    CreateCommand.Set('MaximumY', MaximumY)
                    CreateCommand.Set('AutomaticallyRecalculateExtentsIndicator', AutomaticallyRecalculateExtentsIndicator)
                    CreateCommand.Set('StationListOverride', StationListOverride)
                    CreateCommand.Set('StationSortByDistanceIndicator', StationSortByDistanceIndicator)
                    CreateCommand.Set('DisplayMapOutlineIndicator', DisplayMapOutlineIndicator)
                    CreateCommand.Set('EstimateOnlyIndicator', EstimateOnlyIndicator)
                    CreateCommand.save()               
                    stakerWorkOrder.Name=Name
                    stakerWorkOrder.Description=Description
                    stakerWorkOrder.HazardsAssociatedWithJobIndicator=HazardsAssociatedWithJobIndicator
                    stakerWorkOrder.WorkProcedureInvolvedIndicator=WorkProcedureInvolvedIndicator
                    stakerWorkOrder.SpecialPrecautionsIndicator=SpecialPrecautionsIndicator
                    stakerWorkOrder.EnergySourceControlsIndicator=EnergySourceControlsIndicator
                    stakerWorkOrder.PPERequirementsIndicator=PPERequirementsIndicator
                    stakerWorkOrder.TailgateDiscussionIndicator=TailgateDiscussionIndicator
                    stakerWorkOrder.CheckWhereSepticTankIsIndicator=CheckWhereSepticTankIsIndicator
                    stakerWorkOrder.WorkPlanReferenceIndicator=WorkPlanReferenceIndicator
                    stakerWorkOrder.NewConstructionIndicator=NewConstructionIndicator
                    stakerWorkOrder.SystemImprovementIndicator=SystemImprovementIndicator
                    stakerWorkOrder.ReplacementIndicator=ReplacementIndicator
                    stakerWorkOrder.Retire_No_ReplacementIndicator=Retire_No_ReplacementIndicator
                    stakerWorkOrder.GeneralFundsIndicator=GeneralFundsIndicator
                    stakerWorkOrder.No_OfServicesOH=No_OfServicesOH
                    stakerWorkOrder.No_OfServicesUG=No_OfServicesUG
                    stakerWorkOrder.Wire=Wire
                    stakerWorkOrder.LoanNo=LoanNo
                    stakerWorkOrder.Substation=Substation
                    stakerWorkOrder.MapNo=MapNo
                    stakerWorkOrder.LocationNextTo=LocationNextTo
                    stakerWorkOrder.CalhounCountyIndicator=CalhounCountyIndicator
                    stakerWorkOrder.OrangeburgCountyIndicator=OrangeburgCountyIndicator
                    stakerWorkOrder.RichlandCountyIndicator=RichlandCountyIndicator
                    stakerWorkOrder.LexingtonCountyIndicator=LexingtonCountyIndicator
                    stakerWorkOrder.SumterCountyIndicator=SumterCountyIndicator
                    stakerWorkOrder.KershawCountyIndicator=KershawCountyIndicator
                    stakerWorkOrder.WorkOrderNumber=WorkOrderNumber
                    stakerWorkOrder.W_P=W_P
                    stakerWorkOrder.N_W_P=N_W_P
                    stakerWorkOrder.EngineerStaked=EngineerStaked
                    stakerWorkOrder.EngineerChecked=EngineerChecked
                    stakerWorkOrder.EngineerReleasedForConst=EngineerReleasedForConst
                    stakerWorkOrder.Co_PermitNo=Co_PermitNo
                    stakerWorkOrder.PUPS=PUPS
                    stakerWorkOrder.NewR_WIndicator=NewR_WIndicator
                    stakerWorkOrder.R_WToBeCutIndicator=R_WToBeCutIndicator
                    stakerWorkOrder.R_WCutDate=R_WCutDate
                    stakerWorkOrder.ExistingR_WIndicator=ExistingR_WIndicator
                    stakerWorkOrder.StakerPhaseStartIndicator=StakerPhaseStartIndicator
                    stakerWorkOrder.StakerPhaseStartDate=StakerPhaseStartDate
                    stakerWorkOrder.OutToConstructionStartIndicator=OutToConstructionStartIndicator
                    stakerWorkOrder.OutToConstructionStartDate=OutToConstructionStartDate
                    stakerWorkOrder.VerificationPhaseStartIndicator=VerificationPhaseStartIndicator 
                    stakerWorkOrder.VerificationPhaseStartDate=VerificationPhaseStartDate
                    stakerWorkOrder.ArchivedIndicator=ArchivedIndicator
                    stakerWorkOrder.ArchivedDate=ArchivedDate
                    stakerWorkOrder.CreateDate=CreateDate
                    stakerWorkOrder.DeletedIndicator=DeletedIndicator
                    stakerWorkOrder.MinimumX=MinimumX
                    stakerWorkOrder.MinimumY=MinimumY
                    stakerWorkOrder.MaximumX=MaximumX
                    stakerWorkOrder.MaximumY=MaximumY
                    stakerWorkOrder.AutomaticallyRecalculateExtentsIndicator=AutomaticallyRecalculateExtentsIndicator
                    stakerWorkOrder.StationListOverride=StationListOverride
                    stakerWorkOrder.StationSortByDistanceIndicator=StationSortByDistanceIndicator
                    stakerWorkOrder.DisplayMapOutlineIndicator=DisplayMapOutlineIndicator
                    stakerWorkOrder.EstimateOnlyIndicator=EstimateOnlyIndicator
                    stakerWorkOrder.save()
    if(DeleteIndicator and (not PerformArchiveTasks) and (not ArchivedIndicator)):
        if(StakerWorkOrderid):
            command=Command()
            command=command.Create(Name='DeleteStakerWorkOrder', StakerWorkOrderid=StakerWorkOrderid, CommandUserName=UserName)
            stakerWorkOrder=command.Process()
    elif(UndeleteIndicator and (not PerformArchiveTasks) and (not ArchivedIndicator)):
        if(StakerWorkOrderid):
            command=Command()
            command=command.Create(Name='UndeleteStakerWorkOrder', StakerWorkOrderid=StakerWorkOrderid, CommandUserName=UserName)
            stakerWorkOrder=command.Process()        
    ArchiveFinalImageFileName=None
    if(ArchivedScannedWorkOrderFile and stakerWorkOrder and (PerformArchiveTasks or not ArchivedIndicator)):
        BaseFileName=str(ArchivedScannedWorkOrderFile).split('.')[0]
        Extension=str(ArchivedScannedWorkOrderFile).split('.')[-1] 
        ArchiveFinalImageFileName=str(StakerWorkOrderid) + '.' + Extension
        destination=open(djangoproject.settings.MEDIA_ROOT + 'stakerworkorderscanned/' + ArchiveFinalImageFileName, 'wb+')
        for chunk in ArchivedScannedWorkOrderFile.chunks():
            destination.write(chunk)
        destination.close()
        os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderscanned/') 
        stakerWorkOrder.ArchivedScannedWorkOrderFileName=ArchiveFinalImageFileName
        stakerWorkOrder.save()
    if(ArchivedInspectedWorkOrderFile):
        BaseFileName=str(ArchivedInspectedWorkOrderFile).split('.')[0]
        Extension=str(ArchivedInspectedWorkOrderFile).split('.')[-1] 
        InspectFinalImageFileName=str(StakerWorkOrderid) + '.' + Extension
        destination=open(djangoproject.settings.MEDIA_ROOT + 'stakerworkorderinspected/' + InspectFinalImageFileName, 'wb+')
        for chunk in ArchivedInspectedWorkOrderFile.chunks():
            destination.write(chunk)
        destination.close()
        os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderinspected/') 
        stakerWorkOrder.ArchivedInspectedWorkOrderFileName=InspectFinalImageFileName
        stakerWorkOrder.save()

    #If there are duplicate Staker Work Order Numbers, clear the number of the one just changed and return a message
    try:
        LastFive=WorkOrderNumber[-5:]
    except:
        LastFive=''
    StakerWorkOrderNumberMessage=''
    if(len(LastFive)==5 and stakerWorkOrder):
        PossibleDuplicateStakerWorkOrder=StakerWorkOrder.objects.filter(WorkOrderNumber__iendswith=LastFive)
        if(PossibleDuplicateStakerWorkOrder.count() > 1):
            StakerWorkOrderNumberMessage='Duplicate Work Order Number:  ' + LastFive
            try:  #Change all the objects that might have modified the staker work order in this pass through this function
                CreateCommand.Set('WorkOrderNumber', '')
                CreateCommand.save()
            except:
                pass
            try:
                command.Set('WorkOrderNumber', '')
                command.save()
            except:
                pass
            try:
                stakerWorkOrder.WorkOrderNumber=''
                stakerWorkOrder.save()
            except:
                pass
    if(not stakerWorkOrder):
        try:
            stakerWorkOrder=StakerWorkOrder.objects.filter(id=StakerWorkOrderid)[0]
        except:
            pass
    return stakerWorkOrder, SelectedWorkOrderid, ArchiveStatusMessage, StakerWorkOrderNumberMessage

def PopulateStakerForm(form, stakerWorkOrder, SelectedWorkOrderid, UserName):
    #All actions have been completed, now populate the form fields with the appropriate results
    #Get the Selected Staker Work Order now if there is a selection
    if(SelectedWorkOrderid):
        try:
            stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=SelectedWorkOrderid)[0]
        except:
            stakerWorkOrder=None
    try:
        ClearFormIndicator=bool(form.data['ClearFormIndicator'] == 'on')
    except:
        ClearFormIndicator=False
    if(ClearFormIndicator):
        stakerWorkOrder=None
    form.data['ClearFormIndicator']=False

    try:
        form.data['DeleteIndicator']=False
        form.data['UndeleteIndicator']=False
        form.data['Name']=str(stakerWorkOrder.Name)
        form.data['StakerWorkOrderUserName']=stakerWorkOrder.UserName
        form.data['StakerWorkOrderChangeUserNameIndicator']=False
        form.data['StakerWorkOrders']=str(stakerWorkOrder.id)
        form.data['StakerWorkOrderid']=str(stakerWorkOrder.id)
        form.data['Description']=str(stakerWorkOrder.Description)
        form.data['HazardsAssociatedWithJobIndicator']=stakerWorkOrder.HazardsAssociatedWithJobIndicator
        form.data['WorkProcedureInvolvedIndicator']=stakerWorkOrder.WorkProcedureInvolvedIndicator
        form.data['SpecialPrecautionsIndicator']=stakerWorkOrder.SpecialPrecautionsIndicator
        form.data['EnergySourceControlsIndicator']=stakerWorkOrder.EnergySourceControlsIndicator
        form.data['PPERequirementsIndicator']=stakerWorkOrder.PPERequirementsIndicator
        form.data['TailgateDiscussionIndicator']=stakerWorkOrder.TailgateDiscussionIndicator
        form.data['CheckWhereSepticTankIsIndicator']=stakerWorkOrder.CheckWhereSepticTankIsIndicator
        form.data['WorkPlanReferenceIndicator']=stakerWorkOrder.WorkPlanReferenceIndicator
        form.data['NewConstructionIndicator']=stakerWorkOrder.NewConstructionIndicator
        form.data['SystemImprovementIndicator']=stakerWorkOrder.SystemImprovementIndicator
        form.data['ReplacementIndicator']=stakerWorkOrder.ReplacementIndicator
        form.data['Retire_No_ReplacementIndicator']=stakerWorkOrder.Retire_No_ReplacementIndicator
        form.data['GeneralFundsIndicator']=stakerWorkOrder.GeneralFundsIndicator
        if(stakerWorkOrder.No_OfServicesOH):
            form.data['No_OfServicesOH']=str(stakerWorkOrder.No_OfServicesOH)
        else: 
            form.data['NoOfServicesOH']=''
        if(stakerWorkOrder.No_OfServicesUG):
            form.data['No_OfServicesUG']=str(stakerWorkOrder.No_OfServicesUG)
        else:
            form.data['No_OfServicesUG']=''
        form.data['Wire']=str(stakerWorkOrder.Wire)
        form.data['LoanNo']=str(stakerWorkOrder.LoanNo)
        form.data['Substation']=str(stakerWorkOrder.Substation)
        form.data['MapNo']=str(stakerWorkOrder.MapNo)
        form.data['LocationNextTo']=str(stakerWorkOrder.LocationNextTo)
        form.data['CalhounCountyIndicator']=stakerWorkOrder.CalhounCountyIndicator
        form.data['OrangeburgCountyIndicator']=stakerWorkOrder.OrangeburgCountyIndicator
        form.data['LexingtonCountyIndicator']=stakerWorkOrder.LexingtonCountyIndicator
        form.data['RichlandCountyIndicator']=stakerWorkOrder.RichlandCountyIndicator
        form.data['KershawCountyIndicator']=stakerWorkOrder.KershawCountyIndicator
        form.data['SumterCountyIndicator']=stakerWorkOrder.SumterCountyIndicator
        form.data['WorkOrderNumber']=str(stakerWorkOrder.WorkOrderNumber)
        form.data['W_P']=str(stakerWorkOrder.W_P)
        form.data['N_W_P']=str(stakerWorkOrder.N_W_P)
        form.data['EngineerStaked']=str(stakerWorkOrder.EngineerStaked)
        form.data['EngineerChecked']=str(stakerWorkOrder.EngineerChecked)
        form.data['EngineerReleasedForConst']=str(stakerWorkOrder.EngineerReleasedForConst)
        form.data['Co_PermitNo']=str(stakerWorkOrder.Co_PermitNo)
        form.data['PUPS']=str(stakerWorkOrder.PUPS)
        form.data['NewR_WIndicator']=stakerWorkOrder.NewR_WIndicator
        form.data['R_WToBeCutIndicator']=stakerWorkOrder.R_WToBeCutIndicator
        form.data['R_WCutDate']=str(stakerWorkOrder.R_WCutDate)
        form.data['ExistingR_WIndicator']=stakerWorkOrder.ExistingR_WIndicator
        form.data['StakerPhaseStartIndicator']=stakerWorkOrder.StakerPhaseStartIndicator
        form.data['StakerPhaseStartDate']=stakerWorkOrder.StakerPhaseStartDate
        form.data['OutToConstructionStartIndicator']=stakerWorkOrder.OutToConstructionStartIndicator
        form.data['OutToConstructionStartDate']=stakerWorkOrder.OutToConstructionStartDate
        form.data['VerificationPhaseStartIndicator']=stakerWorkOrder.VerificationPhaseStartIndicator 
        form.data['VerificationPhaseStartDate']=stakerWorkOrder.VerificationPhaseStartDate
        form.data['ArchivedIndicator']=stakerWorkOrder.ArchivedIndicator
        form.data['ArchivedDate']=stakerWorkOrder.ArchivedDate
        form.data['CreateDate']=stakerWorkOrder.CreateDate
        form.data['DeletedIndicator']=stakerWorkOrder.DeletedIndicator
        form.data['EstimateOnlyIndicator']=stakerWorkOrder.EstimateOnlyIndicator
        form.data['AutomaticallyRecalculateExtentsIndicator']=False
        form.data['StartPhaseOutToConstructionIndicator']=False
        form.data['StartPhaseVerificationIndicator']=False
        form.data['StartPhaseArchiveIndicator']=False
        form.data['CancelPhaseOutToConstructionIndicator']=False
        form.data['CancelPhaseVerificationIndicator']=False
        form.data['MinimumX']=stakerWorkOrder.MinimumX
        form.data['MinimumY']=stakerWorkOrder.MinimumY
        form.data['MaximumX']=stakerWorkOrder.MaximumX
        form.data['MaximumY']=stakerWorkOrder.MaximumY
        try:
            form.data['StationListOverride']=stakerWorkOrder.StationListOverride
        except:
            form.data['StationListOverride']=''
        try:
            form.data['StationSortByDistanceIndicator']=stakerWorkOrder.StationSortByDistanceIndicator
        except:
            form.data['StationSortByDistanceIndicator']=False
        form.data['ArchivedScannedWorkOrderFileName']=''
        form.data['ArchivedInspectedWorkOrderFileName']=''
        form.data['SelectWorkOrderNumber']=''
        form.data['DisplayMapOutlineIndicator'] = stakerWorkOrder.DisplayMapOutlineIndicator
    except AttributeError:
        form.data['DeleteIndicator']=False
        form.data['UndeleteIndicator']=False
        form.data['Name']=''
        form.data['StakerWorkOrderUserName']=UserName
        form.data['StakerWorkOrderChangeUserNameIndicator']=False
        form.data['StakerWorkOrderid']=''
        form.data['Description']=''
        form.data['HazardsAssociatedWithJobIndicator']=False
        form.data['WorkProcedureInvolvedIndicator']=False
        form.data['SpecialPrecautionsIndicator']=False
        form.data['EnergySourceControlsIndicator']=False
        form.data['PPERequirementsIndicator']=False
        form.data['TailgateDiscussionIndicator']=False
        form.data['CheckWhereSepticTankIsIndicator']=False
        form.data['WorkPlanReferenceIndicator']=False
        form.data['NewConstructionIndicator']=False
        form.data['SystemImprovementIndicator']=False
        form.data['ReplacementIndicator']=False
        form.data['Retire_No_ReplacementIndicator']=False
        form.data['GeneralFundsIndicator']=False
        form.data['No_OfServicesOH']=''
        form.data['No_OfServicesUG']=''
        form.data['Wire']=''
        form.data['LoanNo']=''
        form.data['Substation']=''
        form.data['MapNo']=''
        form.data['LocationNextTo']=''
        form.data['CalhounCountyIndicator']=False
        form.data['OrangeburgCountyIndicator']=False
        form.data['LexingtonCountyIndicator']=False
        form.data['RichlandCountyIndicator']=False
        form.data['KershawCountyIndicator']=False
        form.data['SumterCountyIndicator']=False
        form.data['EstimateOnlyIndicator']=False
        form.data['WorkOrderNumber']=''
        form.data['W_P']=''
        form.data['N_W_P']=''
        form.data['EngineerStaked']=''
        form.data['EngineerChecked']=''
        form.data['EngineerReleasedForConst']=''
        form.data['Co_PermitNo']=''
        form.data['PUPS']=''
        form.data['NewR_WIndicator']=False
        form.data['R_WToBeCutIndicator']=''
        form.data['R_WCutDate']=''
        form.data['ExistingR_WIndicator']=False
        form.data['StakerPhaseStartIndicator']=False
        form.data['StakerPhaseStartDate']=''
        form.data['OutToConstructionStartIndicator']=False
        form.data['OutToConstructionStartDate']=''
        form.data['VerificationPhaseStartIndicator']=False 
        form.data['VerificationPhaseStartDate']=''
        form.data['ArchivedIndicator']=False
        form.data['ArchivedDate']=''
        form.data['CreateDate']=''
        form.data['DeletedIndicator']=False
        form.data['CalculateExtentsIndicator']=False
        form.data['StartPhaseOutToConstructionIndicator']=False
        form.data['StartPhaseVerificationIndicator']=False
        form.data['StartPhaseArchiveIndicator']=False
        form.data['CancelPhaseOutToConstructionIndicator']=False
        form.data['CancelPhaseVerificationIndicator']=False
        form.data['MinimumX'] = ''
        form.data['MinimumY'] = ''
        form.data['MaximumX'] = ''
        form.data['MaximumY'] = ''
        form.data['StationListOverride']=''
        form.data['StationSortByDistanceIndicator']=False
        form.data['ArchivedScannedWorkOrderFileName']=''
        form.data['ArchivedInspectedWorkOrderFileName']=''  
        form.data['SelectWorkOrderNumber']=''
        form.data['DisplayMapOutlineIndicator']=False
    if(stakerWorkOrder):    #Used now to create the link in the template to the edit details page
        SelectedWorkOrderid=str(stakerWorkOrder.id)
    else:
        SelectedWorkOrderid='-1'  #-1 is the explicit none 
    return SelectedWorkOrderid




def ProcessStakerSummary(form, stakerWorkOrder):
    try:
        ShowSummaryIndicator=bool(form.data['ShowSummaryIndicator'] == 'on')
    except:
        ShowSummaryIndicator=False
    if(ShowSummaryIndicator):
        StakerWorkOrderSummary=COOPGIS_ReportLabStakerReport.GetTableData(stakerWorkOrder, SkipColors=True)        
    else:
        StakerWorkOrderSummary=[[]]
    return ShowSummaryIndicator, StakerWorkOrderSummary


def AttemptToArchive(request, stakerWorkOrder, UserName):
    """AttemptToArchive Verifies that a Staker Work Order has a Scanned Image, generates a new generated image, sets Install Assemblies to Install, and 
    Deletes Assemblies that should be removed (using commands)"""
    from djangoproject.models import *
    if(not djangoproject.settings.COOPGISServerIndicator):
        return 'Attempt To Archive failed because the Server Indicator is not set.', False
    if(not stakerWorkOrder.ArchivedScannedWorkOrderFileName):
        return 'Attempt To Archive failed because a Scanned Copy of the final work order has not been uploaded.', False
    stakerWorkOrder.UpdatePolygon()
    GenerateReportDetails(stakerWorkOrder.id, UserName)  #Will generate the final report and save it to the final location
    Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder).order_by('id')
    Position=0
    CurrentStationSpanRecipeList=[]
    while(Position < len(Assemblies)):  #Recipes Consume Assemblies, so avoid for loop
        StartAssemblyLength=len(Assemblies)
        i=Assemblies[Position]
        if(i.Station):
            StationOrSpanid=i.Station.id
        else:
            StationOrSpanid=i.Span.id
        if(i.StakerRecipeNumber): #Attempt to apply a recipe only once per recipe # per Station OR Span
            UniqueIdentifier=(str(i.StakerRecipeNumber) + '   spanstation    ' + str(i.Station.id) + str(StationOrSpanid)) #Make unique even if spanid=stationid=recipeid
            if(not UniqueIdentifier in CurrentStationSpanRecipeList):
                CurrentStationSpanRecipeList.append(UniqueIdentifier)
                stakerRecipe=StakerRecipe()
                stakerRecipe.ApplyRecipe(i, UserName, TestOnly=False)
        Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder).order_by('id')
        Position = Position + 1
        if(StartAssemblyLength > len(Assemblies)):
            Position = Position - 1

    for i in Assemblies:
        if(i.InstallStatus.Name == 'Install'):  #Commands to create the assemblies would exist as long term records
            NewStakerAssemblyHistory=StakerAssemblyHistory()
            NewStakerAssemblyHistory.CompatibleUnit=i.CompatibleUnit
            if(i.Station):
                NewStakerAssemblyHistory.Point=i.Station.Point
            else: 
                NewStakerAssemblyHistory.Line=i.Span.Line
            NewStakerAssemblyHistory.StakerWorkOrder=stakerWorkOrder
            NewStakerAssemblyHistory.InstallIndicator=True
            NewStakerAssemblyHistory.RemoveIndicator=False
            NewStakerAssemblyHistory.Date=datetime.date.today()
            NewStakerAssemblyHistory.save()
            i.InstallStatus=InstallStatus.objects.filter(Name__exact='Existing')[0]
            i.save()
            if(i.Station):
                i.Station.RebuildSymbology()
            else:
                i.Span.RebuildSymbology()
        elif(i.InstallStatus.Name == 'Remove'): 
            NewStakerAssemblyHistory=StakerAssemblyHistory()
            NewStakerAssemblyHistory.CompatibleUnit=i.CompatibleUnit
            if(i.Station):
                NewStakerAssemblyHistory.Point=i.Station.Point
            else: 
                NewStakerAssemblyHistory.Line=i.Span.Line
            NewStakerAssemblyHistory.StakerWorkOrder=stakerWorkOrder
            NewStakerAssemblyHistory.InstallIndicator=False
            NewStakerAssemblyHistory.RemoveIndicator=True
            NewStakerAssemblyHistory.Date=datetime.date.today()
            NewStakerAssemblyHistory.save()
            ArchiveDeleteAssembly(i.id, UserName)
    return str(stakerWorkOrder.id) + ' Staker Work Order has successfully been applied to the map and archived.', True


def ArchiveDeleteAssembly(Assemblyid, UserName):
    """Returns the Order of the command deleted if deleting a command was necessary, otherwise returns 0 if successful"""
    AssemblyToDelete=Assembly.objects.filter(id=Assemblyid)[0]
    if(AssemblyToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeleteAssembly', Assemblyid=Assemblyid, CommandUserName=UserName)
        command=command.Process()
        return 0
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        commandid=int(str(AssemblyToDelete.CreateCommand.id)) #int(str()) to force the query to execute before the deletion
        if(AssemblyToDelete.Station):
            StationOrSpan=AssemblyToDelete.Station
        else:
            StationOrSpan=AssemblyToDelete.Span
        AssemblyToDelete.delete()
        command=Command.objects.filter(id__exact=commandid)
        Order=command[0].Order
        command[0].delete()
        StationOrSpan.RebuildSymbology()
        return Order



def GenerateReportDetails(StakerWorkOrderid, UserName, ViewScannedOnly=False, ViewInspectedOnly=False):
    stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=int(StakerWorkOrderid))[0]
    if(not stakerWorkOrder.ArchivedIndicator and not ViewScannedOnly and not ViewInspectedOnly):
        try:
            MapFile=ApplicationDefaultMap.objects.filter(ApplicationName__exact=djangoproject.settings.COOPGISStakerApplicationName,\
                    UserName__exact=UserName)[0].Map
        except:
            MapFile=ApplicationDefaultMap.objects.filter(ApplicationName__exact=djangoproject.settings.COOPGISStakerApplicationName,\
                    UserName__exact='')[0].Map
        MapFileName=MapFile.GenerateMapFile(UserName, djangoproject.settings.COOPGISStakerApplicationName)
        SelectionPoint.objects.filter(UserName__exact=UserName).delete()  #Delete any yellow Highlighted Points before creating the Staker Work Order
        SelectionLine.objects.filter(UserName__exact=UserName).delete() #Delete any yellow Highlighted Points before creating the Staker Work Order
        if(not(os.path.exists('/var/www/coopgisstakerworkorders/'))):
            os.system("sudo -u apachescript sudo mkdir /var/www/coopgisstakerworkorders/") 
        os.system("sudo -u apachescript sudo chmod -R 777 /var/www/coopgisstakerworkorders/")
        COOPGIS_ReportLabStakerReport.Create(stakerWorkOrder, MapFileName)
        GenerateReportStatus='A Staker Report was generated for ' + str(stakerWorkOrder.id) + ':  ' + stakerWorkOrder.Name
    elif(ViewScannedOnly):
        #Rename Any work orders that have a .PDF extension to a .pdf extension, then copy it so it is accessible
        os.system("sudo -u apachescript sudo mv " + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderscanned/' + str(stakerWorkOrder.id) + 
                  '.PDF ' + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderscanned/' + str(stakerWorkOrder.id) + '.pdf')
        os.system("sudo -u apachescript sudo cp " + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderscanned/' + str(stakerWorkOrder.id) + 
                  '.pdf /var/www/coopgisstakerworkorders/' + str(stakerWorkOrder.id) + '.pdf')
        os.system('sudo -u apachescript sudo chmod -R 777 /var/www/coopgisstakerworkorders/')
        GenerateReportStatus='Follow the link for a scanned archive of the Staker Report'
    else: #View Inspected Only Section
        #raise(Exception('Made it here Inspected'))
        #Rename Any work orders that have a .PDF extension to a .pdf extension, then copy it so it is accessible
        os.system("sudo -u apachescript sudo mv " + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderinspected/' + str(stakerWorkOrder.id) + 
                  '.PDF ' + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderinspected/' + str(stakerWorkOrder.id) + '.pdf')
        os.system("sudo -u apachescript sudo cp " + djangoproject.settings.MEDIA_ROOT + 'stakerworkorderinspected/' + str(stakerWorkOrder.id) + 
                  '.pdf /var/www/coopgisstakerworkorders/' + str(stakerWorkOrder.id) + '.pdf')
        os.system('sudo -u apachescript sudo chmod -R 777 /var/www/coopgisstakerworkorders/')
        GenerateReportStatus='Follow the link for an inspected archive of the Staker Report'
    ReportLocation='/coopgisstakerworkorders/' + str(StakerWorkOrderid) + '.pdf'
    return GenerateReportStatus, ReportLocation



def GetNearbyTags(assembly):
    Stations=[]
    if(assembly.Station):
        Stations.append(assembly.Station)
    else:
        Stations.append(assembly.Span.StartStation)
        Stations.append(assembly.Span.EndStation)
    TagNumberList=[]
    for station in Stations:
        Assemblies=Assembly.objects.filter(Station=station).exclude(TagNumber='').exclude(TagNumber=None)
        for i in Assemblies:
            TagNumberList.append(i.TagNumber)
    if(TagNumberList):
        return ', '.join(TagNumberList)
    else:
        return ''


def BuildStakerQuickGenerateForm(DefaultMap, Assemblies):
    from django.contrib import admin
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    #Create InstallStatus Choices
    InstallStatusChoices=[]
    InstallStatusInstall=InstallStatus.objects.filter(Name='Install')[0]
    InstallStatusChoices.append([InstallStatusInstall.id, str(InstallStatusInstall)])
    InstallStatuses=InstallStatus.objects.all().exclude(Name='Install').order_by('Name')
    for i in InstallStatuses:
        InstallStatusChoices.append([i.id, str(i)])
    NumberOfAssemblies=len(Assemblies)
    for i in range(0, NumberOfAssemblies):
        Dict['StakerWorkOrderid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['CompatibleUnit' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['InstallStatus' + str(i)]=forms.ChoiceField(choices=InstallStatusChoices, required=False)
        Dict['Stationid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['Spanid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['DisassociateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['Assemblyid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['TagNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['WKTPolygon']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['DeletePolygonIndicator']=forms.BooleanField(required=False)
    return Dict



def ProcessStakerQuickGenerateForm(form, stakerWorkOrder, UserName):
    if(not stakerWorkOrder):
        return
    #Process Assembly Changes Section 
    i = -1
    while(True):
        i = i + 1
        try:
            Assemblyid=int(form.data['Assemblyid' + str(i)])
        except:
            break
        try:
            DisassociateIndicator=bool(form.data['DisassociateIndicator' + str(i)] == 'on')
        except:
            DisassociateIndicator=False
        try:
            InstallStatusid=int(form.data['InstallStatus' + str(i)])
            installStatus=InstallStatus.objects.filter(id__exact=InstallStatusid)[0]
            InstallStatusName=installStatus.Name
        except IOError:
            InstallStatusName='Existing'
        assembly=Assembly.objects.filter(id=Assemblyid)[0]
        if(assembly.InstallStatus.Name == InstallStatusName and not DisassociateIndicator):
            continue  #Do not make a command to modify an assembly if no changes are being made by this form
        if(assembly.ResidesOnServerIndicator):
            if(DisassociateIndicator):
                StakerWorkOrderid = None
                StakerWorkOrderIndexWhenReverseSorted=-1
            else:
                StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=stakerWorkOrder.GetCommandidData()
            tempcommand=command.Command().Create(Name='EditAssembly', Assemblyid=Assemblyid, AssemblyName=assembly.CompatibleUnit.Name,  
                                 TagNumber=assembly.TagNumber, 
                                 PutIntoServiceDate=assembly.PutIntoServiceDate, PrimaryIndicator=assembly.PrimaryIndicator, 
                                 SecondaryIndicator=assembly.SecondaryIndicator, ServiceIndicator=assembly.ServiceIndicator, 
                                 PoleStubIndicator=assembly.PoleStubIndicator,             
                                 PoleLightIndicator=assembly.PoleLightIndicator, PoleGuyIndicator=False, 
                                 PoleMeterIndicator=assembly.PoleMeterIndicator, OwnerName=assembly.GetAssemblyOwnerName(), 
                                 ManufacturerName=assembly.GetManufacturerName(), 
                                 MeterFormName=assembly.GetMeterFormName(), OpenIndicator=assembly.OpenIndicator,  
                                 MeterOnPoleIndicator=assembly.MeterOnPoleIndicator, 
                                 PhaseAIndicator=assembly.PhaseAIndicator, PhaseBIndicator=assembly.PhaseBIndicator,
                                 PhaseCIndicator=assembly.PhaseCIndicator, PhaseNeutralIndicator=assembly.PhaseNeutralIndicator, 
                                 CircuitNumber=assembly.CircuitNumber,
                                 SerialNumber=assembly.SerialNumber, MeterNumber=assembly.MeterNumber, MeterDCSINumber=assembly.MeterDCSINumber,
                                 MapNumber=assembly.MapNumber, OldMapNumber=assembly.OldMapNumber,
                                 SubstationName=assembly.SubstationName, 
                                 TransformerCompletelySelfProtectedIndicator=assembly.TransformerCompletelySelfProtectedIndicator,
                                 MeterServiceTypeName=assembly.GetMeterServiceTypeName(), 
                                 CommandUserName=UserName,
                                 PhysicalAddress=assembly.PhysicalAddress, IdleIndicator=assembly.IdleIndicator, InstallStatus=InstallStatusName,
                                 StakerWorkOrderid=StakerWorkOrderid, StakerWorkOrderIndexWhenReverseSorted=StakerWorkOrderIndexWhenReverseSorted,
                                 StakerRecipeNumber=assembly.StakerRecipeNumber)
            tempcommand.Process()
        else:  #If the assembly does not reside on the server 
            tempcommand=command.Command.objects.filter(id=assembly.CreateCommand.id)[0]
            tempcommand.Set('InstallStatus', InstallStatusName)
            tempcommand.Set('StakerWorkOrderid', StakerWorkOrderid)
            tempcommand.save()
            assembly.InstallStatus=installStatus
            assembly.StakerWorkOrder=stakerWorkOrder
            assembly.save()
            assembly.Station.RebuildSymbology()
            
    #Process Polygon Changes Section
    polygon=COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTPolygon')
    try:
        stakerQuickGeneratePolygon=StakerQuickGeneratePolygon.objects.filter(StakerWorkOrder=stakerWorkOrder)[0]
    except:
        stakerQuickGeneratePolygon=StakerQuickGeneratePolygon()
        stakerQuickGeneratePolygon.StakerWorkOrder=stakerWorkOrder
    DeletePolygonIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeletePolygonIndicator')
    if(DeletePolygonIndicator):
        polygon=None
    if(polygon or DeletePolygonIndicator):
        stakerQuickGeneratePolygon.Polygon=polygon
        stakerQuickGeneratePolygon.save()
    return stakerQuickGeneratePolygon.Polygon

def PopulateStakerQuickGenerateForm(form, stakerWorkOrder, Assemblies):
    NumberOfAssemblies=len(Assemblies)
    for i in range(0, NumberOfAssemblies):
        try:
            form.data['StakerWorkOrderid' + str(i)] = Assemblies[i].StakerWorkOrder.id
        except:
            form.data['StakerWorkOrderid' + str(i)] = ''
        if(Assemblies[i].TagNumber):
            form.data['TagNumber' + str(i)] = Assemblies[i].TagNumber
        else:
            form.data['TagNumber' + str(i)] = ''
        form.data['CompatibleUnit' + str(i)] = Assemblies[i].CompatibleUnit.Name
        form.data['InstallStatus' + str(i)] = Assemblies[i].InstallStatus.id
        try:
            form.data['Stationid' + str(i)] = Assemblies[i].Station.id
        except:
            form.data['Stationid' + str(i)] = ''
        try:
            form.data['Spanid' + str(i)] = Assemblies[i].Span.id
        except:
            form.data['Spanid' + str(i)] = ''
        form.data['DisassociateIndicator' + str(i)] = False
        form.data['Assemblyid' + str(i)] = Assemblies[i].id
    #Does not work to populate the openlayers map with the preselected polygon FIXME********************************
    try:
        stakerQuickGeneratePolygon=StakerQuickGeneratePolygon.objects.filter(StakerWorkOrder=stakerWorkOrder)[0]
    except:
        stakerQuickGeneratePolygon=None
    form.data['DeletePolygonIndicator']=False
    if(stakerQuickGeneratePolygon):
        form.data['Polygon']=str(stakerQuickGeneratePolygon.Polygon)
        form.fields['WKTPolygon'].initial=str(stakerQuickGeneratePolygon.Polygon)
    else:
        form.data['WKTPolygon']=''
    return form

